//
//  NSMutableArray+SafeMethod.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "NSMutableArray+SafeMethod.h"

@implementation NSMutableArray (SafeMethod)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class cls = objc_getClass("__NSArrayM");
        SEL originalSelector = @selector(objectAtIndex:);
        SEL swizzledSelector = @selector(py_objectAtIndex:);
        
        Method originalMethod = class_getInstanceMethod(cls, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);
        
        BOOL didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (didAddMethod) {
            NSLog(@"didAddMethod");
            class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        } else {
            NSLog(@"didnotAddMethod");
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

- (nullable id)py_objectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        return [self py_objectAtIndex:index];
    } else {
        NSLog(@"可变数组越界，%@", self);
        return nil;
    }
}
@end
